package jgl.vajra.management.part.mine.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.CarDetailsBean;
import jgl.vajra.management.bean.PeripheralPoiBean;
import jgl.vajra.management.databinding.ActivityCarDetailsBinding;
import jgl.vajra.management.dialogFragment.CertificationAuditDialogFragment;
import jgl.vajra.management.event.MapPointEvent;
import jgl.vajra.management.listener.MessageDlialogListener;
import jgl.vajra.management.manager.AccountManager;
import jgl.vajra.management.manager.FragmentManager;
import jgl.vajra.management.manager.ImageShowManager;
import jgl.vajra.management.manager.IntentManager;
import jgl.vajra.management.part.mine.contract.CarDetailsContract;
import jgl.vajra.management.part.mine.viewModel.CarDetailsViewModel;
import jgl.vajra.management.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.management.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.management.widget.dialogfragment.MessageDialogFragment;
import jgl.vajra.management.widget.manager.RxJavaHttpManager;
import jgl.vajra.management.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.management.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.management.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.management.widget.utils.DisplayUtils;
import jgl.vajra.management.widget.utils.UIUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@CreateViewModel(CarDetailsViewModel.class)
public class CarDetailsActivity extends BaseMVVMActivity<CarDetailsViewModel, ActivityCarDetailsBinding> implements CarDetailsContract.View, BaseBindingItemPresenter<String> {

    private String logo;
    private SingleTypeBindingAdapter adapter;
    private MessageDialogFragment messageDialogDeleteCar;
    private MessageDialogFragment messageDialogAdditional;
    private int hasCannonHead;
    private CarDetailsBean data;
    private int tag;
    private CertificationAuditDialogFragment certificationAuditDialogFragment;

    @Override
    public int getLayoutId() {
        return R.layout.activity_car_details;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        logo = getIntent().getStringExtra("logo");
        String title = getIntent().getStringExtra("title");
        tag = getIntent().getIntExtra("tag", 1);

        mBinding.toolbar.setTitleText(title);

        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new SingleTypeBindingAdapter(this, null, R.layout.item_car_details);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);
       /* adapter.setItemDecorator((BaseDataBindingDecorator<String, ItemCarDetailsBinding>) (binding, position, viewType, data) -> {

            // 不可嵌套滑动
            binding.itemRecyclerView.setNestedScrollingEnabled(false);
            // 取消head 的 recycleView的焦点
            binding.itemRecyclerView.setFocusableInTouchMode(false);
            //设置布局管理器
            binding.itemRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
            SingleTypeBindingAdapter itemAdapter = new SingleTypeBindingAdapter(this, null, R.layout.item_car_details_item);
            binding.itemRecyclerView.setAdapter(itemAdapter);

        });*/

        requestNetData();
    }

    private void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("logo", logo);
        map.put("tag", tag);
        mViewModel.getCarDetailsData(map);
    }

    //审核
    @Override
    public void onDetermine(String logo) {
        certificationAuditDialogFragment = new CertificationAuditDialogFragment();
        certificationAuditDialogFragment.setData(tag, logo);
        certificationAuditDialogFragment.setCertificationAuditListener(new CertificationAuditDialogFragment.CertificationAuditListener() {
            @Override
            public void onDetermine() {
                finish();
            }
        });
        certificationAuditDialogFragment.show(getSupportFragmentManager());
    }

    @Override
    public void onResidentAddress(CarDetailsBean data) {
        IntentManager.toMapPointActivity(this);
    }

    //是否有炮头
    @Override
    public void onGunHead() {
        Map<String, Object> map = new HashMap<>();
        map.put("logo", data.logo);

        if (messageDialogAdditional == null) {
            messageDialogAdditional = FragmentManager.getMessageDialogAdditional(new MessageDlialogListener() {
                @Override
                public void onRightClick() {
                    hasCannonHead = 2;
                    mBinding.tvGunHead.setText("是");

                    map.put("hasCannonHead", hasCannonHead);
                    modifyCarInformation(map);
                }

                @Override
                public void onLeftClick() {
                    hasCannonHead = 1;
                    mBinding.tvGunHead.setText("否");

                    map.put("hasCannonHead", hasCannonHead);
                    modifyCarInformation(map);
                }
            });
        }
        messageDialogAdditional.show(getSupportFragmentManager());
    }

    //图片1
    @Override
    public void onImageView(int type) {
        switch (type) {
            case 1:
                IntentManager.toBitmapImageNetActivity(this, data.credentialsPicture.get(0).bucketName, data.credentialsPicture.get(0).fileKey);
                break;
            case 2:
                if (data.credentialsPicture.size() >= 2)
                    IntentManager.toBitmapImageNetActivity(this, data.credentialsPicture.get(1).bucketName, data.credentialsPicture.get(1).fileKey);
                break;
            case 3:
                IntentManager.toBitmapImageNetActivity(this, data.insurancePicture.get(0).bucketName, data.insurancePicture.get(0).fileKey);
                break;
            case 4:
                if (data.insurancePicture.size() >= 2)
                    IntentManager.toBitmapImageNetActivity(this, data.insurancePicture.get(1).bucketName, data.insurancePicture.get(1).fileKey);
                break;

            case 5:
                IntentManager.toBitmapImageNetActivity(this, data.operatePicture.get(0).bucketName, data.operatePicture.get(0).fileKey);
                break;
            case 6:
                if (data.operatePicture.size() >= 2)
                    IntentManager.toBitmapImageNetActivity(this, data.operatePicture.get(1).bucketName, data.operatePicture.get(1).fileKey);
                break;

            case 7:
                IntentManager.toBitmapImageNetActivity(this, data.otherPicture.get(0).bucketName, data.otherPicture.get(0).fileKey);
                break;
            case 8:
                if (data.otherPicture.size() >= 2)
                    IntentManager.toBitmapImageNetActivity(this, data.otherPicture.get(1).bucketName, data.otherPicture.get(1).fileKey);
                break;

        }

    }


    @Override
    public void returnCarDetailsData(CarDetailsBean data) {
        this.data = data;
        mBinding.setData(data);
        if (tag == 1) {
            adapter.refresh(data.carPicture);
        } else {
            adapter.refresh(data.publicizePicture);
        }

        setPictureData(data.credentialsPicture, mBinding.llCredentialsPicture, mBinding.imageView1, mBinding.imageView2);
        setPictureData(data.insurancePicture, mBinding.llInsurancePicture, mBinding.imageView3, mBinding.imageView4);
        setPictureData(data.operatePicture, mBinding.llOperatePicture, mBinding.imageView5, mBinding.imageView6);
        setPictureData(data.otherPicture, mBinding.llOtherPicture, mBinding.imageView7, mBinding.imageView8);
    }

    public void setPictureData(List<CarDetailsBean.PictureBean> dataPicture, LinearLayout llView, ImageView imageView1, ImageView imageView2) {
        if (dataPicture == null || dataPicture.size() == 0) {
            //隐藏
            llView.setVisibility(View.GONE);
        } else if (dataPicture.size() == 1) {
            setPictureShow(imageView1, dataPicture.get(0));
        } else {
            setPictureShow(imageView1, dataPicture.get(0));
            setPictureShow(imageView2, dataPicture.get(1));
        }
    }

    public void setPictureShow(ImageView imageView, CarDetailsBean.PictureBean itemData) {
       /* Map<String, Object> maps = new HashMap<>();
        maps.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        maps.put("bucketName", itemData.bucketName);
        maps.put("fileKey", itemData.fileKey);
        RetrofitJsonManager.getInstance().getApiService().getDetailsImageData(maps)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(false, null) {
                    @Override
                    public void _onNext(String data) {

                        //将Base64编码字符串解码成Bitmap
                        byte[] decodedString = Base64.decode(data, Base64.DEFAULT);
                        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        //设置ImageView图片
//                        imageView.setImageBitmap(getRoundedCornerBitmap(decodedByte));

                        RequestOptions options = new RequestOptions().transform(new CenterCrop(), new RoundedCorners((int) DisplayUtils.getDimension(R.dimen.dp_10)));
                        Glide.with(CarDetailsActivity.this)
                                .asBitmap()
                                .load(decodedByte)
                                .apply(options)
                                .into(new BitmapImageViewTarget(imageView) {
                                    @Override
                                    protected void setResource(Bitmap resource) {
                                        super.setResource(resource);
                                        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                                        imageView.setImageDrawable(roundedBitmapDrawable);
                                    }
                                });

                    }
                });*/

        ImageShowManager.getInstance().setPictureShow(this,imageView,itemData.bucketName,itemData.fileKey);

        /*OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse("https://steel.vin:29318/files/get-image")
                .newBuilder();
        *//* reqBuild.addHeader("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJwaG9uZSI6ImxOQ095aWpFNEgvUDArbzFza2lvbGc9PSIsImludml0YXRpb24iOiI1ODQwNTA1NzEyIiwidXNlclR5cGUiOiIyIiwianRpIjoiODg5ZTBkZjktY2UwOS00NTEzLTlhZjAtYTRkYWM2YjdlNTdjIiwiZXhwIjoxNjY2MjQ0MTQ4fQ.DkJ083vRn5eyHNAe0jZcn22OP3WIKeScdmsbhluMyg5TyEIzdjcn1A-Wgl3zBdP7pacwW1MT2nT_wvu2P3P6-T5lotXR-95rF_Lv_WtwbBUej__u2ra2UvDlWLp0cRjmXlD4N_eiqxlIl3MmXCszF3ZAOvtZPXdXj6o6loetFnEhAua_jQff5EHFvk7Yz8Fo0x1wbWVLnMcJPFMUxcHKwxhj2iPV58zOlVkwe2gXPRWVoXphNWxT4UQ4EoNfBqeqhrP9FDKk8tMG-O7gu8pbRPd8-Ki3TBjiz3aWQsPd_rVaEeUT4WpQtZDbRFtEUZZ3z-BbNz-CwCwLStgtIjG-nQ");*//*
        reqBuild.addHeader("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        reqBuild.addHeader("bucketName", itemData.bucketName);
        reqBuild.addHeader("fileKey", itemData.fileKey);

        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.d("onFailure", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    byte[] content = response.body().bytes();
                    CarDetailsActivity.this.runOnUiThread(() -> {
                        Bitmap bmp = BitmapFactory.decodeByteArray(content, 0, content.length);
                        imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, imageView.getWidth(),
                                imageView.getHeight(), false));
                        Logger.e("response is ==", content.toString());
                    });

                }
            }
        });*/
    }


    @Override
    public void returnDeleteCarData() {
        finish();
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMapPointEvent(MapPointEvent event) {
        PeripheralPoiBean addressBean = event.bean;
        String address = addressBean.address + addressBean.detailedAddress;
        mBinding.tvAddress.setText(address);
        mBinding.tvAddress.setTextColor(UIUtils.getColor(R.color.color_333333));

        Map<String, Object> map = new HashMap<>();
        map.put("logo", data.logo);
        map.put("longitude", addressBean.longitude);
        map.put("latitude", addressBean.latitude);
        map.put("address", address);
        map.put("city", addressBean.city);

        modifyCarInformation(map);
    }

    private void modifyCarInformation(Map<String, Object> map) {
        mViewModel.modifyCarData(map);
    }

    @Override
    public void onItemClick(int position, String itemData) {
        List<String> list;
        if (tag == 1) {
            list = data.carPicture;
        } else {
            list = data.publicizePicture;
        }

        IntentManager.toBigImageNetActivity(this, list, position);
    }
}
